from pandas import DataFrame

from tools import *
import json

from tools.entity import MySignals


# 策略基类, 产生买卖信号
class Stg:
    code = None

    data: DataFrame = None

    # 默认参数
    param = {}

    index = 0

    signals = {}  # 买卖信号, 格式=时间:信号, 1=买入, -1=卖出

    def getStgName(self):
        return self.__class__.__name__

    def getParams(self) -> list[dict]:
        return [{}]

    def initial(self):
        return

    def signal(self, index):
        return None

    def getPriceDetail(self, offset=0):
        """
        :param offset: 偏移天数
        :return: 每日价格详细数据, 包含键:  ts_code, trade_date, open, high, low, close, pre_close,
                change(涨跌额), pct_chg(涨跌幅), vol(成交量), amount(成交额)
        """
        return self.data.loc[self.index + offset]

    def getPrice(self, offset=0):
        """
        :param offset: 偏移天数
        :return:
        """
        return self.data.close[self.index + offset]

    def run(self, uuid):
        self.initial()
        self.signals = {}
        for i in range(0, len(self.data)):
            self.index = i
            signal = self.signal(i)
            if signal is not None and signal != 0:
                self.signals[str(self.data.trade_date[i])] = signal
        if len(self.signals) == 0:
            return self.signals
        # 保存信号
        mySignals = MySignals(stg=self.__class__.__name__, code=self.code, param=json.dumps(self.param),
                              detail=json.dumps(self.signals), sid=uuid)
        tool.log(mySignals)
        dbTool.save(mySignals)
        return self.signals
